package com.donn.securitycontrolplatform.rpmClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class RpmClient {

    @Autowired
    private static RestTemplate template;


    public String post(String url) {
        return post(url, null);
    }

    public String post(String url, MultiValueMap<String, Object> paramMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("charset", "UTF-8");
        return post(url, headers, paramMap);
    }

    public String post(String url, HttpHeaders headers, MultiValueMap<String, Object> paramMap) {
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<String> response = template.postForEntity(url, httpEntity, String.class);
        if (response.getStatusCode() == HttpStatus.ALREADY_REPORTED) {
            return response.getBody();
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        RestTemplate template=new RestTemplate();
//        String url = "http://127.0.0.1:8081/channel/channelHourData/getHourNewUserData";
        String url = "http://192.168.253.201:8081/channel/channelHourData/getHourNewUserData";

        // 封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("dt", "20180416");

        // 1、使用postForObject请求接口
        String result = template.postForObject(url, paramMap, String.class);
        System.out.println("result1==================" + result);

        // 2、使用postForEntity请求接口
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("charset", "UTF-8");
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
        System.out.println("result2====================" + response2.getBody());

        // 3、使用exchange请求接口
        ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);
        System.out.println("result3====================" + response3.getBody());
    }

}

